﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections;
using GridLayoutAPI.Models;
using Newtonsoft.Json;

namespace GridLayoutAPI.Controllers
{
    public class APIController : Controller
    {
        
        GridLayoutDataContext db = new GridLayoutDataContext();
        List<Allitems> itmlist = null;
        
        List<MySubscribe> itmsubs = null;


        public ActionResult Index()
        {
            return View();
        }

        #region NewItem
        //Users can add new item.Params are:
        //id: itemid  that to be added
        //userid:who add this new item.owner of this item.
        //parentid:parent under which item is added
        //order: order no of an item
        //title:title of item
        //type:level of item.type can be leaf or nonleaf.<0:for leaf item, 1:for non-leaf item>

        #endregion
        public ActionResult addItem(int Userid, int parentid, int order, string title, string thumburl, int type)
        {
            Itemclass iItem = new GridLayoutAPI.Models.Itemclass();
            Data idata = new Data();
            try
            {
                var lastid = (from p in db.Items
                           select p.ItemId).Max();
                Item itm = new Item
                {
                    
                    ItemId = lastid+1,
                    OwnerId = Userid,
                    ParentId = parentid,
                    OrderNo = order,
                    ThumbnailUrl = thumburl,
                    ItemLevel = type,
                    Version=1,
                    Title = title,
                    CreationDatetime = DateTime.Now

                };
             
                db.Items.InsertOnSubmit(itm);
                db.SubmitChanges();
                idata.itemid = Convert.ToInt32(itm.ItemId);
                idata.versionid = Convert.ToInt32(itm.Version);
                iItem.data = idata;
                iItem.status = 1;
                iItem.HttpRespose = "Register Successful";
                // return Content(JsonConvert.SerializeObject(iItem));
                return Content(JsonConvert.SerializeObject(iItem));
            }
            catch (Exception ex)
            {
                iItem.HttpRespose = ex.Message;
                iItem.status = 0;
                return Content(JsonConvert.SerializeObject(iItem));

            }

        }

        #region clone item
        //copy of an item is generated according to itemid and versionid that we pass.
        // items are cloned of one another have same item ID, but different version Id
        #endregion
        public ActionResult cloneItem(int userId, int itemid,int versionid)
        {
            GridLayoutDataContext db1 = new GridLayoutDataContext();
            Itemdetail iItem = new Itemdetail();
            Document idata = new Document();
            List<Schedule> schList = new List<Schedule>();
            ItemMessage iMsg = new ItemMessage();
            List<Outlines> Outlist = new List<Outlines>();
            List<Document> Doclist = new List<Document>();
           
            
            Item itm = db1.Items.Where(k => k.ItemId == itemid && k.Version==versionid ).SingleOrDefault();
            {
                if (itm != null)
                {
                    Int32 version = Convert.ToInt32(itm.Version);
                    Int32 newversion = version + 1;
                   
                    try
                    {
                        Item itm1 = new Item
                        {
                            ItemId = itemid,
                            Version = newversion,
                            ParentId = itm.ParentId,
                            OwnerId = itm.OwnerId,
                            OriginalVersionId = itm.Version,
                            OrderNo = itm.OrderNo,
                            ThumbnailUrl = itm.ThumbnailUrl,
                            Description = itm.Description,
                            Title = itm.Title,
                            SubTitle=itm.SubTitle,
                            ResourceId=itm.ResourceId,
                            OutlineId=itm.OutlineId,
                            OwnerName = itm.OwnerName,
                            CreationDatetime = DateTime.Now



                        };
                        db.Items.InsertOnSubmit(itm1);
                        db.SubmitChanges();

                        iItem.itemid = itm1.ItemId;
                        iItem.versionid = itm1.Version;

                        iItem.title = itm1.Title;
                        iItem.subtitle = itm1.SubTitle;
                        iItem.description = itm1.Description;
                        IEnumerable<SessionSchedule> sess = db.SessionSchedules.Where(ss => ss.ItemId == itm1.ItemId).ToList();
                        if (sess.Count() != 0)
                        {
                            foreach (var al in sess)
                            {
                                Schedule iSch = new Schedule();
                                iSch.id = Convert.ToInt32(al.SessionId);
                                // TimeSpan diff = Convert.ToDateTime(sess.TimeEnd) - Convert.ToDateTime(sess.TimeStart);
                                iSch.name = al.SessionName;
                                iSch.startime = Convert.ToDateTime(al.TimeStart);
                                iSch.endime = Convert.ToDateTime(al.TimeEnd);
                                schList.Add(iSch);
                            }
                        }

                        iItem.schedule = schList;      

                        //   Resource res = db.Resources.Where(k => k.ResourceId == itm1.ResourceId).SingleOrDefault();
                        //   if (res != null)
                        //   {
                        //       idata.name = res.ResTitle;
                        //       idata.url = res.Url;

                        //   }
                        //   iItem.documents = idata;
                      //  Outline outln = db.Outlines.Where(ot => ot.ItemId == itm1.ItemId).SingleOrDefault();
                      //  if (outln != null)
                      //  {
                      //      iOut.name = outln.OutlineName;
                      //      iOut.url = outln.OutlineUrl;

                      //  }
                      // iItem.outline = iOut;

                        IEnumerable<ItemResource> itmres = db.ItemResources.Where(r => r.ItemId == itm1.ItemId && r.ItemVersion == itm1.Version).ToList();
                        if (itmres.Count() != 0)
                        {
                            foreach (var al in itmres)
                            {

                                Document idoc = new Document();
                                if (al.Association == "doc")
                                {
                                    idoc.id = Convert.ToInt32(al.ResourceId);
                                    Resource res = db.Resources.Where(rs => rs.ResourceId == al.ResourceId).SingleOrDefault();

                                    idoc.name = res.ResName;
                                    idoc.url = res.Url;
                                    Doclist.Add(idoc);

                                }
                                else
                                {
                                    Outlines iOut = new Outlines();
                                    iOut.id = Convert.ToInt32(al.ResourceId);
                                    Resource res = db.Resources.Where(rs => rs.ResourceId == al.ResourceId).SingleOrDefault();

                                    iOut.name = res.ResName;
                                    iOut.url = res.Url;
                                    Outlist.Add(iOut);
                                }
                            }

                        }
                        iItem.documents = Doclist;
                        iItem.outline = Outlist;
                        return Content(JsonConvert.SerializeObject(iItem));   
                   
                    }
                    catch (Exception ex)
                    {

                        iMsg.HttpRespose = ex.Message;
                        return Content(JsonConvert.SerializeObject(iMsg));
                    }
                }
                else
                {
                    iMsg.HttpRespose = "Invalid ItemID or Version";
                    return Content(JsonConvert.SerializeObject(iMsg));
                }
            }
        }

        public ActionResult addGroup(int Userid, int parentid, int order, string title, string thumburl,string subtitle,string description,string backgroundimage)
        {
            GroupClass igrp = new GridLayoutAPI.Models.GroupClass();
            Data iData = new Data();
            try
            {
                Group grp = new Group
                {

                    UserId = Userid,
                    ParentId = parentid,
                    OrderNO = order,
                    Thumbnail = thumburl,
                    GroupTitle = title,
                    GroupSubtitle=subtitle,
                    Description=description,
                    BackGroundImage=backgroundimage
                    


                };
                db.Groups.InsertOnSubmit(grp);
                db.SubmitChanges();
               
                igrp.groupid = Convert.ToInt32(grp.GroupId);
                igrp.status = 1;
               
                igrp.HttpRespose = "create group Successful";
               
                return Content(JsonConvert.SerializeObject(igrp));
            }
            catch (Exception ex)
            {
                igrp.HttpRespose = ex.Message;
                igrp.status = 0;
                return Content(JsonConvert.SerializeObject(igrp));

            }

        }

        #region update item
        //item's title,description,itemmodifytime and document is updated according to itemid and version id we pass
        #endregion
        public ActionResult updateItem(int id, int versionid,
            String title,
            String Description,
            int resourceid
           
            )
        {
            Item itm = db.Items.First(k => k.ItemId == id && k.Version == versionid);
            Itemclass iItem = new Itemclass();
            Schedule sch = new Schedule();
            if (itm != null)
            {
                try
                {

                    itm.Title = title;
                    itm.Description = Description;
                    itm.ModifyDatetime = DateTime.Now;
                    itm.ResourceId = resourceid;
                    db.SubmitChanges();
                    iItem.HttpRespose = "Item Updated Successfully";
                    return Content(JsonConvert.SerializeObject(iItem));

                }
                catch (Exception ex)
                {
                    iItem.HttpRespose = ex.Message;
                    return Content(JsonConvert.SerializeObject(iItem));
                }
            }
            else
            {
                iItem.HttpRespose = "Invalid item ID or version ";
                return Content(JsonConvert.SerializeObject(iItem));
            }

        }


        #region Itemdetail
        // we get single item detail by passing item id and item version
        #endregion
        public ActionResult getItemDetail(int id, int version)
        {
            Itemdetail iItem = new Itemdetail();
            Document idata = new Document();
           
            ItemMessage iMsg = new ItemMessage();
            List<Outlines> Outlist = new List<Outlines>();
            List<Document> Doclist = new List<Document>();
            List<Schedule> schList = new List<Schedule>();
            schList = null;
            try
            {

                Item itms = db.Items.Where(k => k.ItemId == id && k.Version == version).SingleOrDefault();
                if (itms != null)
                {
                    iItem.itemid = itms.ItemId;
                    iItem.versionid = itms.Version;

                    iItem.title = itms.Title;
                    iItem.subtitle = itms.SubTitle;
                    iItem.description = itms.Description;

                    
                    IEnumerable<ItemResource> itmres = db.ItemResources.Where(r => r.ItemId == itms.ItemId && r.ItemVersion == itms.Version).ToList();
                    if (itmres.Count() != 0)
                    {
                        foreach (var al in itmres)
                        {

                            Document idoc = new Document();
                            if (al.Association == "doc")
                            {
                                idoc.id = Convert.ToInt32(al.ResourceId);
                                Resource res = db.Resources.Where(rs => rs.ResourceId == al.ResourceId).SingleOrDefault();

                                idoc.name = res.ResName;
                                idoc.url = res.Url;
                                Doclist.Add(idoc);                               
                                
                            }
                            else
                            {
                                Outlines iOut = new Outlines();
                                iOut.id = Convert.ToInt32(al.ResourceId);
                                Resource res = db.Resources.Where(rs => rs.ResourceId == al.ResourceId).SingleOrDefault();

                                iOut.name = res.ResName;
                                iOut.url = res.Url;                               
                                Outlist.Add(iOut);
                            }
                        }

                    }
                    iItem.documents = Doclist;
                    iItem.outline = Outlist;
                    IEnumerable< SessionSchedule> sess = db.SessionSchedules.Where(ss => ss.ItemId == itms.ItemId).ToList();
                    if (sess.Count()!=0)
                    {
                        foreach (var al in sess)
                        {
                            Schedule iSch = new Schedule();
                            iSch.id = Convert.ToInt32(al.SessionId);
                            // TimeSpan diff = Convert.ToDateTime(sess.TimeEnd) - Convert.ToDateTime(sess.TimeStart);
                            iSch.name = al.SessionName;
                            iSch.startime = Convert.ToDateTime(al.TimeStart);
                            iSch.endime = Convert.ToDateTime(al.TimeEnd);
                            schList.Add(iSch);
                        }
                    }
                   
                    iItem.schedule = schList;                 
                    return Content(JsonConvert.SerializeObject(iItem));
                }
                else
                {

                    iMsg.HttpRespose = "Invalid Id or Version";
                    return Content(JsonConvert.SerializeObject(iMsg));
                }
            }
            catch (Exception ex)
            {

                iMsg.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iMsg));
            }
        }
        #region update GroupOrder
        //params are: parentid,groupid, order
        
        // group order is updated to order which we pass ,according to groupid and parent id .

        #endregion
        public ActionResult updateGroupOrder(int groupid, int order)
        {
            GroupClass Igroup = new GroupClass();
            Group grp = db.Groups.Where(k => k.GroupId == groupid).SingleOrDefault();
            if (grp != null)
            {
                try
                {
                    grp.OrderNO = order;
                    db.SubmitChanges();
                    Igroup.HttpRespose = "Group order is updated successfully";
                    return Content(JsonConvert.SerializeObject(Igroup));
                }
                catch (Exception ex)
                {
                    Igroup.HttpRespose = ex.Message;
                    return Content(JsonConvert.SerializeObject(Igroup));
                }

            }
            else
            {
                Igroup.HttpRespose = "Invalid group ID";
                return Content(JsonConvert.SerializeObject(Igroup));

            }



        }

        public ActionResult updateItemOrder( int itemid, int version, int order)
        {
            GroupClass Igroup = new GroupClass();
            Item itm = db.Items.Where(k => k.ItemId == itemid && k.Version == version ).SingleOrDefault();
            if (itm != null)
            {
                try
                {
                    itm.OrderNo = order;
                    db.SubmitChanges();
                    Igroup.HttpRespose = "Item order is updated successfully";
                    return Content(JsonConvert.SerializeObject(Igroup));
                }
                catch (Exception ex)
                {
                    Igroup.HttpRespose = ex.Message;
                    return Content(JsonConvert.SerializeObject(Igroup));
                }

            }
            else
            {
                Igroup.HttpRespose = "Invalid item ID or Version ";
                return Content(JsonConvert.SerializeObject(Igroup));

            }



        }
        #region allitems
        // get all items  of a group according to groupid we pass
        #endregion

        public ActionResult getItems(int groupid, int offset, int limit)
        {
            Itemclass iItem = new Itemclass();
            Allitems Alitm = new Allitems();
            if(itmlist==null)
            itmlist = new List<Allitems>();
            
            try
            {
                

                IEnumerable<Item> itms = db.Items.Where(k => k.GroupId == groupid).Skip(offset).Take(limit).ToList();
                if (itms != null)
                {
                    //foreach (var al in itms)
                    //{
                        
                    //    Group grp=db.Groups.Where(gr=>gr.GroupId==al.GroupId).SingleOrDefault();
                    //    Alitm.group = grp.GroupTitle;
                    //    Alitm.title = al.Title;
                    //    Alitm.subtitle = al.SubTitle;
                    //    Alitm.description = al.Description;
                    //    Alitm.backimage = al.BackGroungImage;
                    //    Alitm.version = al.Version;
                    //    Alitm.visits =Convert.ToInt32( al.Visits);
                    //    Alitm.rank = Convert.ToInt32(al.Ranking);
                    //    itmlist.Add(Alitm);
                    //}

                    return Content(JsonConvert.SerializeObject(itms));
                }
                else
                {

                    iItem.HttpRespose = "No child group regarding this item";
                    return Content(JsonConvert.SerializeObject(iItem));
                }
            }
            catch (Exception ex)
            {

                iItem.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iItem));
            }
        }


        #region getversion
        // ge all versions of an item according to itemid we pass
        #endregion


        public ActionResult getVersions(int id, int offset, int limit)
        {
            Itemclass iItem = new Itemclass();
            Data idata = new Data();
            List<ItemVersion> itmvrsn = new List<ItemVersion>();
            try
            {
                offset = 0;

                //IEnumerable<Item>  itms = db.Items.Where(k => k.ItemId ==itemid ).Skip(offset).Take(limit).ToList();

                var itmss = (from p in db.Items where p.ItemId == id select p).Skip(offset).Take(limit).ToList();

                if (itmss != null)
                {
                   
                    foreach (var vr in itmss)
                    {
                        ItemVersion Ivrsion = new ItemVersion();
                        Ivrsion.version = vr.Version;
                        Ivrsion.owner = vr.OwnerName;
                        Ivrsion.backgroundimage = vr.BackGroundImage;
                        Ivrsion.visits =Convert.ToInt32( vr.Visits);
                        itmvrsn.Add( Ivrsion);
                           
                    }
                    
                    return Content(JsonConvert.SerializeObject(itmvrsn));
                }
                else
                {

                    iItem.HttpRespose = "Item does not exist";
                    return Content(JsonConvert.SerializeObject(iItem));
                }
            }
            catch (Exception ex)
            {

                iItem.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iItem));
            }
        }

        #region getgroup
        // get all group of an Parent item
        #endregion
        public ActionResult getGroups(int id, int offset, int limit)
        {
            Itemclass iItem = new Itemclass();
            List<Group> grplist =new List<Group>();
            ItemMessage iMsg = new ItemMessage();
            try
            {
                offset = 0;
                
               // IEnumerable<Item> itms = db.Items.Where(k => k.ParentId == id).Skip(offset).Take(limit).ToList();
                IEnumerable<Group> grp = db.Groups.Where(k => k.ParentId == id).Skip(offset).Take(limit).ToList();
                if (grp != null)
                {
                    
                    return Content(JsonConvert.SerializeObject(grp));
                }
                else
                {
                    iMsg.HttpRespose = "Invalid ParentId";
                    return Content(JsonConvert.SerializeObject(iMsg));
 
                }
            }
            catch (Exception ex)
            {

                iMsg.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iMsg));
            }
        }

        #region Update group id for Items
        //As owner of items can move them around on the screen, update groupId for the items.
        #endregion
        public ActionResult updateGroupsItems(int groupId,int itemId)
        {
            Itemclass iItem = new Itemclass();
            Data iData = new Data();
            try
            {
                IEnumerable<Item> itm = db.Items.Where(k => k.ItemId == itemId).ToList();
               
                if (itm.Count()!=0)
                {
                    try
                    {
                        foreach (var it in itm)
                        {
                            it.GroupId = groupId;
                        }
                        db.SubmitChanges();

                        iItem.status = 1;
                        iItem.HttpRespose = "GroupItems  Updated Successfully";
                        return Content(JsonConvert.SerializeObject(iItem));

                    }
                    catch (Exception ex)
                    {
                        iData.itemid = itemId;
                        iData.Groupid = groupId;
                        iItem.data = iData;
                        iItem.status = 0;
                        iItem.HttpRespose = ex.Message;
                        return Content(JsonConvert.SerializeObject(iItem));
                    }
                }
                else
                {
                    iItem.HttpRespose = "Invalid Item ID ";
                    return Content(JsonConvert.SerializeObject(iItem));
                }
            }
            catch (Exception ex)
            {
                iData.itemid = itemId;
                iData.Groupid = groupId;
                iItem.data = iData;
                iItem.status = 0;
                iItem.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iItem));
            }
        }

        #region Create Session
        //User can create many session for an item.
        //Params: {<itemId>,<versionId>, <timeStart>,<timeEnd>, creator:<userId>, 
        // status is 1 by default
        #endregion

        public ActionResult createSession(int itemid, int version, DateTime starttime, DateTime endtime,
            int userid)
        {
                 Itemclass iItem = new GridLayoutAPI.Models.Itemclass();
            
            Data idata = new Data();
            try
            {
               SessionSchedule sess = new SessionSchedule()
                {
                    ItemId =itemid,
                    VersionId=version,
                    TimeStart=starttime,
                    TimeEnd=endtime,
                    UserId=userid,
                    Status=1


                };
                db.SessionSchedules.InsertOnSubmit(sess);
                db.SubmitChanges();
                
                iItem.status = 1;
                iItem.HttpRespose = "New Session  created";
                // return Content(JsonConvert.SerializeObject(iItem));
                return Content(JsonConvert.SerializeObject(iItem));
            }
            catch (Exception ex)
            {
                iItem.HttpRespose = ex.Message;
                iItem.status = 0;
                return Content(JsonConvert.SerializeObject(iItem));

            }
        }
        #region updateSession
       // Session creator can update status for only sessions created by him and if timeEnd has not passed.
        //Prameters are-
        //int userid:user which update session
        //int sessionid:which session is updated
        //datetime Currentime:time that compared to session endtime
        //int status: that has to be updated according to session id and userid
        #endregion


        public ActionResult updateSession(int userid, int sessionid, DateTime currenttime,int status,DateTime starttime,DateTime endtime)
        {
            ItemMessage iMsg = new ItemMessage();
            try
            {
                SessionSchedule sessusr = db.SessionSchedules.Where(s => s.UserId == userid && s.SessionId == sessionid).SingleOrDefault();
                if (sessusr != null)
                {
                    if (currenttime < sessusr.TimeEnd)
                    {
                        sessusr.Status = status;
                        sessusr.TimeStart = starttime;
                        sessusr.TimeEnd = endtime;
                        db.SubmitChanges();
                        iMsg.HttpRespose = "session updated";
                        return Content(JsonConvert.SerializeObject(iMsg));
                    }
                    else
                    {
                        iMsg.HttpRespose = "Session EndTime expired";
                        return Content(JsonConvert.SerializeObject(iMsg));
                    }
                }
                else
                {
                    iMsg.HttpRespose = "Not a valid User";
                    return Content(JsonConvert.SerializeObject(iMsg));
                }
            }
            catch (Exception ex)
            {
                iMsg.HttpRespose =ex.Message;
                return Content(JsonConvert.SerializeObject(iMsg));
            }
        }


        #region Get All Sessions of an item
        
       // Params: {item:<itemId>, version:<versionId} 
        #endregion
        public ActionResult getAllSessions(int itemid, int version)
        {

            List<Schedule> Schdl = new List<Schedule>();
            ItemMessage iMsg = new ItemMessage();
            UsersDetail usr = new UsersDetail();
            try
            {
                IEnumerable<SessionSchedule> sess = db.SessionSchedules.Where(ss => ss.ItemId == itemid && ss.VersionId == version).OrderBy(o=>o.TimeStart).ToList();
                if (sess != null)
                {
                    foreach (var s in sess)
                    {

                        Schedule iSch = new Schedule();
                        iSch.id = Convert.ToInt32(s.SessionId);
                        iSch.startime = Convert.ToDateTime(s.TimeStart);
                        iSch.endime = Convert.ToDateTime(s.TimeEnd);
                        iSch.userid = Convert.ToInt32(s.UserId);
                        UsersDetail ud = db.UsersDetails.Where(u => u.UserID == s.UserId).SingleOrDefault();
                        iSch.username = ud.UserName;
                        IEnumerable<Subscription> sb = db.Subscriptions.Where(k => k.SessionId == s.SessionId).ToList();
                        iSch.subscribers = sb.Count();
                        Schdl.Add(iSch);
                    }
                    return Content(JsonConvert.SerializeObject(Schdl));
                }
                else
                {
                    iMsg.HttpRespose = "Invalid Item or version";
                    return Content(JsonConvert.SerializeObject(iMsg));
 
                }
            }
            catch (Exception ex)
            {

                iMsg.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iMsg));
            }
        }

        public ActionResult createSubscription(int sessionid,int userid)
        {
            Itemclass iItem = new Itemclass();
            try
            {
                Subscription subs = new Subscription()
                {
                    SessionId = sessionid,
                    UserId = userid,
                    Created = DateTime.Now,
                    Status=1

                };
                db.Subscriptions.InsertOnSubmit(subs);
                db.SubmitChanges();
                iItem.status = 1;
                iItem.HttpRespose = "Subscription created successfully";
                return Content(JsonConvert.SerializeObject(iItem));
            }
               catch (Exception ex)
            {
                iItem.HttpRespose = ex.Message;
                iItem.status = 0;
                return Content(JsonConvert.SerializeObject(iItem));

            }
        }

        public ActionResult updateSubscription(int subscribeid)
        {
            ItemMessage iMsg = new ItemMessage();
            try
            {
                Subscription subs = db.Subscriptions.Where(s => s.SubscripId == subscribeid).SingleOrDefault();
                if (subs != null)
                {
                    subs.Status = 2;
                    db.SubmitChanges();
                    iMsg.HttpRespose = "Subscription is updated";
                    return Content(JsonConvert.SerializeObject(iMsg));
                }
                else
                {
                    iMsg.HttpRespose = "Invalid SubscripId";
                    return Content(JsonConvert.SerializeObject(iMsg));
                }
            }
            catch (Exception ex)
            {
                iMsg.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iMsg));
            }

        }

        #region  Get Item Resources
       // Users Can get All Item Resources by passing item id and version and his userID

        #endregion
        public ActionResult getItemsResources(int id, int version, int userId)
        {
            ItemMessage iMsg = new ItemMessage();
            List<MyResource> ResItmlist = new List<MyResource>();
            try
            {
                IEnumerable<ItemResource> itms = db.ItemResources.Where(k => k.ItemId == id && k.ItemVersion==version && k.UserId==userId).ToList();
                if (itms.Count()!=0)
                {
                    foreach (var al in itms)
                    {

                        MyResource Resitm = new MyResource();
                        Resitm.id = Convert.ToInt32(al.ResourceId);
                        Resource res = db.Resources.Where(rs => rs.ResourceId == al.ResourceId).SingleOrDefault();
                        Resitm.name = res.ResName;
                        Resitm.url = res.Url;
                        Resitm.assoc = al.Association;
                        Resitm.orderno = Convert.ToInt32(al.OrderNO);
                        ResItmlist.Add(Resitm);              
                    }

                    return Content(JsonConvert.SerializeObject(ResItmlist));
                }
                else
                {

                  iMsg.HttpRespose = "Invalid Item or User ";
                  return Content(JsonConvert.SerializeObject(iMsg));
                }
            }
            catch (Exception ex)
            {

                 iMsg.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iMsg));
            }
        }

        #region Get Session Subscribers
       // Get all subscribers of a sessions by passing session id  and status.
        //status: 0 all subscribers, 1: subscribed, 2: unsubscribed
        #endregion
        public ActionResult getSubscribers(int sessionid, int status)
        {
            ItemMessage iMsg = new ItemMessage();
            if (itmsubs == null)
                itmsubs = new List<MySubscribe>();
            try
            {

                if (status == 0)
                {
                    IEnumerable<Subscription> subs = db.Subscriptions.Where(k => k.SessionId == sessionid).ToList();
                    if (subs.Count() != 0)
                    {

                        foreach (var al in subs)
                        {
                            MySubscribe Alitm = new MySubscribe();

                            Alitm.id = Convert.ToInt32(al.UserId);
                            UsersDetail usr = db.UsersDetails.Where(ur => ur.UserID == al.UserId).SingleOrDefault();
                            Alitm.name = usr.UserName;
                            itmsubs.Add(Alitm);
                        }

                        return Content(JsonConvert.SerializeObject(itmsubs));

                    }
                    else
                    {

                        iMsg.HttpRespose = "Invalid Session Id";
                        return Content(JsonConvert.SerializeObject(iMsg));
                    }

                }
                else
                {
                    IEnumerable<Subscription> subs = db.Subscriptions.Where(k => k.SessionId == sessionid && k.Status==status).ToList();
                    if (subs.Count() != 0)
                    {

                        foreach (var al in subs)
                        {
                            MySubscribe Alitm = new MySubscribe();

                            Alitm.id = Convert.ToInt32(al.UserId);
                            UsersDetail usr = db.UsersDetails.Where(ur => ur.UserID == al.UserId).SingleOrDefault();
                            Alitm.name = usr.UserName;
                            itmsubs.Add(Alitm);
                        }

                        return Content(JsonConvert.SerializeObject(itmsubs));

                    }
                    else
                    {

                        iMsg.HttpRespose = "Invalid Session Id";
                        return Content(JsonConvert.SerializeObject(iMsg));
                    }
                }
            }
            catch (Exception ex)
            {

                iMsg.HttpRespose = ex.Message;
                return Content(JsonConvert.SerializeObject(iMsg));
            }
        }

        //The resource here is added to Resource table.
        public ActionResult AddResource(string name,string title,string url,string thumbnailurl)
        {
            AddRes iItem = new GridLayoutAPI.Models.AddRes();

            DataAddRes idata = new DataAddRes();
            try
            {
                Resource sess = new Resource()
                {
                    ResName = name,
                    ResTitle = title,
                    Url = url,
                    ThumbnailUrl = thumbnailurl,  
                    Status=1         
                };
                db.Resources.InsertOnSubmit(sess);
                db.SubmitChanges();

                iItem.status = 1;
                iItem.HttpRespose = "New Resource Created";
                var max = (from p in db.Resources
                           select p.ResourceId).Max();
                idata.id = max;
                iItem.data = idata;
              
                return Content(JsonConvert.SerializeObject(iItem));
            }
            catch (Exception ex)
            {
                iItem.HttpRespose = ex.Message;
                iItem.status = 0;
                return Content(JsonConvert.SerializeObject(iItem));

            }
        }


        //adding an entry to ItemResources table.
          public ActionResult AddResourceToItem(int rId,int itemId,int version,int user,string assoc,short order)
            {
            AddRes iItem = new GridLayoutAPI.Models.AddRes();

            DataAddRes idata = new DataAddRes();
            try
            {
                ItemResource Itmres= new ItemResource()
                {
                    ItemId  = itemId,
                    ItemVersion  = version,
                    ResourceId = rId,
                    UserId = user ,
                    Association =assoc,
                    OrderNO=order,
                    Status=1
                };
                db.ItemResources.InsertOnSubmit(Itmres);
                db.SubmitChanges();

                iItem.status = 1;
                iItem.HttpRespose = "New Item Resource Created";
               
                idata.id = Itmres.ItemResId;
                iItem.data = idata;
              
                return Content(JsonConvert.SerializeObject(iItem));
            }
            catch (Exception ex)
            {
                iItem.HttpRespose = ex.Message;
                iItem.status = 0;
                return Content(JsonConvert.SerializeObject(iItem));

            }
        }

              public ActionResult UpdateResourceItem(int ResourceItemId,int status,string association)
              {
                  AddRes iItem = new GridLayoutAPI.Models.AddRes();

                  DataAddRes idata = new DataAddRes();
                  ItemMessage iMsg = new ItemMessage();
                  try
                  {
                      ItemResource ItmRes=db.ItemResources.Where(itmrs=>itmrs.ItemResId== ResourceItemId && itmrs.Status==status).SingleOrDefault();
                      if (ItmRes != null)
                      {
                          ItmRes.Association = association;
                          db.SubmitChanges();
                          iItem.status = 1;
                          iItem.HttpRespose = "Resource Item is updated";
                          idata.id = ResourceItemId;
                          iItem.data = idata;

                          return Content(JsonConvert.SerializeObject(iItem));
                      }
                      else
                      {
                          iMsg.HttpRespose = "Invalid ResourceItem or Status";
                          return Content(JsonConvert.SerializeObject(iMsg));
                      }
                  }
                  catch (Exception ex)
                  {
                      iItem.HttpRespose = ex.Message;
                      iItem.status = 0;
                      return Content(JsonConvert.SerializeObject(iItem));

                  }
              }




    }
}
